// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// H [author] rhyme_lph
// w [email]  rhymelph@gmail.com
// G [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/page/dashboard/amount_gst/amount_gst_rate_category_page.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/all_reports/fixed_asset/sales_of_fixed_asset_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "salesOfFixedAssetPage")
class SalesOfFixedAssetPage extends StatefulWidget {
  final String assetName;
  final int id;
  final SettingDataCurrency unit;
  final int salesId;
  final String salesPrice;
  final String salesDate;
  final String notes;
  final List<OcrAttachmentEntity> attachments;
  final bool isViewOnly;

  const SalesOfFixedAssetPage(
      {Key key,
      this.assetName,
      this.id,
      this.unit,
      this.notes,
      this.attachments,
      this.isViewOnly,
      this.salesId,
      this.salesPrice,
      this.salesDate})
      : super(key: key);

  @override
  _SalesOfFixedAssetPageState createState() => _SalesOfFixedAssetPageState();
}

class _SalesOfFixedAssetPageState extends State<SalesOfFixedAssetPage>
    with PagePresenter<SalesOfFixedAssetPage, SalesOfFixedAssetProvider> {
  @override
  void initState() {
    if (widget.isViewOnly != null && widget.isViewOnly) {
      provider.isEdit = false;
      provider.attachedFiles = widget.attachments;
      provider.notesController.text = widget.notes;
      provider.salesId = widget.salesId;
    }
    provider.currency = Config.defaultCurrency;
    provider.id = widget.id;
    provider.assetName = widget.assetName;
    if (widget.unit != null) provider.currency = widget.unit;
    if (widget.salesDate != null)
      provider.salesDate = DateTime.tryParse(widget.salesDate);
    if (widget.salesPrice != null)
      provider.salePriceController.text = widget.salesPrice;
    super.initState();
  }

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == false,
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildPopButton() : _buildSaveBtn(),
      );

  Widget _buildPopButton() => listBuilder<Tuple2<bool, List<String>>>(
        selector: (_, __) =>
            Tuple2(!__.isEdit && __.salesId != null, List.from(__.menuList)),
        builder: (BuildContext context, Tuple2<bool, List<String>> value,
                Widget child) =>
            value.item1 != true
                ? Container()
                : NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: provider.menuList,
                  ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
      title: S.current.sales_of_fixed_asset, actions: [rightButton]);

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true,
      builder: (BuildContext context, bool value, Widget child) =>
          FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => ListView(
        children: [
          listBuilder<String>(
            selector: (_, __) => __.assetName,
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.asset_name,
              value: value,
              onTap: widget.assetName == null ? provider.onSelectAsset : null,
            ),
          ),
          listBuilder<String>(
            selector: (_, __) =>
                DateTimeUtils.formatGlobalDateTime(__.salesDate),
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.sales_date,
              value: value,
              onTap:
                  widget.salesDate == null ? provider.onChangeSalesDate : null,
            ),
          ),
          AppSpaces.grayH6,
          listBuilder<String>(
            selector: (_, __) => __.currency?.name,
            builder: (BuildContext context, String value, Widget child) =>
                ValueSelectForm(
              title: S.current.currency,
              value: value,
              onTap:
                  widget.salesPrice == null ? provider.onChangeCurrency : null,
            ),
          ),
          Visibility(
            visible: widget.salesPrice == null,
            child: FromInputField(
              tip: S.current.sales_price,
              controller: provider.salePriceController,
              focusNode: provider.salePriceFocusNode,
              inputFormatterList: [
                doubleInputFormatter,
              ],
              keyboardType: TextInputType.numberWithOptions(decimal: false),
            ),
            replacement: ValueSelectForm(
              value: provider.salePriceController.text,
              title: S.current.sales_price,
            ),
          ),
          AppSpaces.grayH6,
          TextAreaInputForm(
            title: S.current.memo_optional,
            controller: provider.notesController,
            focusNode: provider.notesFocusNode,
          ),
          NormalFormWrapper(
            child: listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
              selector: (_, __) =>
                  Tuple2(List.from(__.files), List.from(__.attachments ?? [])),
              builder: (BuildContext context,
                      Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                      Widget child) =>
                  AttachFileForm(
                onAdd: provider.onAddAttachment,
                files: value.item1,
                onSelectFile: provider.onSelectFile,
                attachments: value.item2,
                onSelectAttachment: provider.onSelectAttachment,
              ),
            ),
          ),
        ],
      );
}
